﻿using I_Ear_Tag.Demoin.EarTagManagement;
using I_Ear_Tag.Infrastructure.Interface;
using I_Ear_Tag.Read.Api.Application.Command.EarTagCommand;
using MediatR;

namespace I_Ear_Tag.Read.Api.Application.CommandHandlers.EarTagHandler
{
    public class EarTagShowCommandHandler : IRequestHandler<EarTagShowCommand, Page<EarTag>>
    {
        private readonly IEarTagRepository earTagRepository;
        public EarTagShowCommandHandler(IEarTagRepository earTagRepository)
        {
            this.earTagRepository = earTagRepository;
        }
        /// <summary>
        /// 显示产羔耳标管理信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Page<EarTag>> Handle(EarTagShowCommand request, CancellationToken cancellationToken)
        {
            var list = await earTagRepository.GetAsync(x=>x.IsDel==true);
            if (!string.IsNullOrEmpty(request.EarNumber))
            {
                list = await earTagRepository.GetAsync(x => x.EarNumber.Contains(request.EarNumber)&&!x.IsDel==false);
            }
            if (request.SheepBreed != null)
            {
                list = await earTagRepository.GetAsync(x => x.SheepBreed == request.SheepBreed && !x.IsDel == false);
            }
            if (request.BirthStatus != null)
            {
                list = await earTagRepository.GetAsync(x => x.BirthStatus == request.BirthStatus && !x.IsDel == false);
            }

            int total = list.Count;
            int pageCount =(int) Math.Ceiling((total * 1.0) / request.pageSize);
            list = list.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            return new Page<EarTag>
            {
                total = total,
                pageCount = pageCount,
                Data = list
            };
        }
    }
}
